package com.study.ratelimit.exception;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.study.ratelimit.utils.ReturnMsg;


/**
 * controller层异常处理类
 */
@RestControllerAdvice
public class ExceptionHandlerAdvice {

	private Logger logger = LoggerFactory.getLogger(ExceptionHandlerAdvice.class);
	
//	private Log logger = LogFactory.get();
	
	@ExceptionHandler
    public ReturnMsg handler(HttpServletRequest req, HttpServletResponse res, Exception e) {
        logger.info("Restful Http请求发生异常...");

        if (res.getStatus() == HttpStatus.BAD_REQUEST.value()) {
            logger.info("修改返回状态值为200");
            res.setStatus(HttpStatus.OK.value());
        }
        
        if (e instanceof NullPointerException) {
            logger.error("代码00：" + e.getMessage());
            return ReturnMsg.fail("发生空指针异常:"+e.getMessage());
        } else if (e instanceof IllegalArgumentException) {
            logger.error("代码01：" + e.getMessage());
            return ReturnMsg.fail("请求参数类型不匹配:"+e.getMessage());
        } else if (e instanceof SQLException) {
            logger.error("代码02：" + e.getMessage());
            return ReturnMsg.fail("数据库访问异常:"+e.getMessage());
        } else if(e instanceof MethodArgumentNotValidException){
            logger.error("代码03：" + e.getMessage());
            return ReturnMsg.fail("参数校检异常:"+e.getMessage());
        }else if(e instanceof BindException){
        	BindException be = (BindException) e;
            logger.error("代码04：" + be.getMessage());
            return ReturnMsg.fail("参数绑定异常:"+be.getAllErrors().get(0).getDefaultMessage());
        } else{
            logger.error("代码99：" + e.getMessage());
            return ReturnMsg.fail("服务器发生异常:"+e.getMessage());
        }
    }
}
